//
//  MYGSettingController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/11.
//

import UIKit

class MYGSettingController: MYGBaseController {
    private var contents: [MYGSettingSection] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
        configCell()
    }
    
    // MARK: - Cell
    private func configCell() {
        contents = []
        let message: MYGSettingSection = MYGSettingSection()
        contents.append(message)
        
        let phone = MYGUserManager.user?.doctor.phone ?? 0
        let phoneItem = MYGSettingCellModel()
        phoneItem.name = "手机号"
        phoneItem.type = .enterText("\(phone)")
        phoneItem.isTop = true
        phoneItem.action = {[weak self] in
            let vc = MYGPhoneBindController()
            self?.present(vc, animated: false)
        }
        
        message.items.append(phoneItem)
        
        let wechatItem = MYGSettingCellModel()
        wechatItem.name = "微信账号"
        wechatItem.type = .enterText("未绑定")
//        message.items.append(wechatItem)
        
        let messageItem = MYGSettingCellModel()
        messageItem.name = "消息通知设置"
        messageItem.type = .button(true)
        messageItem.isBottom = true
//        message.items.append(messageItem)
        
        let other = MYGSettingSection()
        contents.append(other)
        
        let cacheItem = MYGSettingCellModel()
        cacheItem.name = "清理应用缓存"
        cacheItem.type = .text("\(getCacheSize())M")
        cacheItem.isTop = true
        cacheItem.action = { [weak self] in
            self!.clearCache()
        }
        other.items.append(cacheItem)
        
        let privateItem = MYGSettingCellModel()
        privateItem.name = "隐私条款"
        privateItem.type = .enterText("")
        privateItem.action = { [weak self] in
            let vc = MYGProtocolController(titeleName: "隐私条款")
            vc.urlString = privacyUrl
            self?.navigationController?.pushViewController(vc)
        }
        other.items.append(privateItem)
        
        let userItem = MYGSettingCellModel()
        userItem.name = "用户协议"
        userItem.type = .enterText("")
        userItem.action = { [weak self] in
            let vc = MYGProtocolController(titeleName: "用户协议")
            vc.urlString = protoclUrl
            self?.navigationController?.pushViewController(vc)
        }
        other.items.append(userItem)
        
        let serviceItem = MYGSettingCellModel()
        serviceItem.name = "注销"
        serviceItem.type = .enterText("")
        serviceItem.action = { [weak self] in
            MMYGHUD.showToast(text: "会员注销申请已提交，3-5工作日完成审核，审核通过后会删除所有会员相关信息。"){
                self?.logout()
            }
        }
        other.items.append(serviceItem)
        
        tableView.reloadData()
    }
    
    // MARK: - UI
    private func configUI() {
        title = "设置"
        view.addSubview(tableView)
        tableView.tableFooterView?.addSubview(quiteButton)
        
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        quiteButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(28)
            make.top.equalToSuperview().offset(25)
            make.height.equalTo(40)
        }
    }
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .rgba(249, 249, 249, 1)
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 65+bottomSafeheight))
        tableView.tableFooterView?.backgroundColor = .rgba(249, 249, 249, 1)
        tableView.delegate = self
        
        tableView.dataSource = self
        
        tableView.separatorStyle = .none
        tableView.register(cellWithClass: MYGSettingCell.self)
        
        return tableView
    }()
    
    private lazy var quiteButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .rgba(162, 146, 254, 1)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 20
        btn.setTitle("退出登录", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .regular(16)
        btn.addTarget(self, action: #selector(logout), for: .touchUpInside)
        return btn
    }()
}

extension MYGSettingController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents[section].items.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        55
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGSettingCell.self, for: indexPath)
        cell.model = contents[indexPath.section].items[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        15
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 15))
        view.backgroundColor = .rgba(249, 249, 249, 1)
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        contents[indexPath.section].items[indexPath.row].action?()
    }
}

extension MYGSettingController {
    @objc
    private func logout() {
        clearCache()
        MYGUserManager.removeUser()
        MYGSocketManager.shared.disconnect()
        
        UserDefaults.standard.removeObject(forKey: "HomeSortDefalut")
        UserDefaults.standard.synchronize()
        
        let vc = MYGNavigationController(rootViewController: MYGRegisterController())
        UIViewController.keyWindow?.rootViewController = vc
    }
    
    ///获取APP缓存
    func getCacheSize()-> String {
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first

        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)

        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {

            // 把文件名拼接到路径中
            let path = cachePath! + ("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            for (key, fileSize) in floder {
                // 累加文件大小
                if key == FileAttributeKey.size {
                    size += (fileSize as AnyObject).integerValue
                }
            }
        }

        let totalCache = Double(size) / 1024.00 / 1024.00
        return String(format: "%.2f", totalCache)
    }

    ///删除APP缓存
    func clearCache() {
        
        MMYGHUD.showToast(text: "清理成功")
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for file in fileArr! {
            let path = (cachePath! as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                }
            }
        }
       
        configCell()
    }
    
}
